<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>化学老师控制台</title>
    <script src="https://cdn.socket.io/4.5.4/socket.io.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        :root {
            --primary: #4a6fa5;
            --secondary: #6d9eeb;
            --success: #6aa84f;
            --warning: #e69138;
            --danger: #cc0000;
            --light: #f5f5f5;
            --dark: #333;
            --player-color: #d9ead3;
            --teacher-color: #cfe2f3;
            --pending-color: #fff2cc;
            --phase-waiting: #d5a6bd;
            --phase-distributing: #b4a7d6;
            --phase-preparation: #b6d7a8;
            --phase-action: #f9cb9c;
            --phase-defense: #ea9999;
            --phase-settlement: #a2c4c9;
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f0f0f0;
            color: #333;
            line-height: 1.6;
            padding: 20px;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        header {
            background-color: var(--primary);
            color: white;
            padding: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header-info {
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .room-id {
            background-color: rgba(255, 255, 255, 0.2);
            padding: 5px 15px;
            border-radius: 20px;
            font-weight: bold;
        }

        .teacher-indicator {
            background-color: var(--teacher-color);
            color: var(--dark);
            padding: 5px 15px;
            border-radius: 20px;
            font-weight: bold;
        }

        .game-phase {
            padding: 8px 15px;
            border-radius: 5px;
            font-weight: bold;
            text-transform: uppercase;
            letter-spacing: 1px;
            text-align: center;
            min-width: 150px;
        }

        .phase-waiting { background-color: var(--phase-waiting); }
        .phase-distributing { background-color: var(--phase-distributing); }
        .phase-preparation { background-color: var(--phase-preparation); }
        .phase-action { background-color: var(--phase-action); }
        .phase-defense { background-color: var(--phase-defense); }
        .phase-settlement { background-color: var(--phase-settlement); }

        .controls {
            display: flex;
            gap: 10px;
        }

        button {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background-color: var(--secondary);
            color: white;
        }

        .btn-success {
            background-color: var(--success);
            color: white;
        }

        .btn-danger {
            background-color: var(--danger);
            color: white;
        }

        .btn-warning {
            background-color: var(--warning);
            color: white;
        }

        button:hover {
            opacity: 0.9;
            transform: translateY(-2px);
        }

        button:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .main-content {
            display: grid;
            grid-template-columns: 1fr 2fr;
            gap: 20px;
            padding: 20px;
            height: calc(100vh - 180px);
        }

        .player-list {
            background-color: var(--light);
            border-radius: 8px;
            padding: 15px;
            overflow-y: auto;
            max-height: 100%;
        }

        .player-list h2 {
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid var(--secondary);
        }

        .player-card {
            background-color: white;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }

        .player-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }

        .player-name {
            font-weight: bold;
            font-size: 1.1rem;
        }

        .player-status {
            font-size: 0.85rem;
            padding: 3px 8px;
            border-radius: 10px;
            color: white;
        }

        .status-ready { background-color: var(--success); }
        .status-not-ready { background-color: var(--warning); }
        .status-eliminated { background-color: var(--danger); }

        .player-info {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
        }

        .health-bar {
            height: 20px;
            background-color: #e0e0e0;
            border-radius: 10px;
            overflow: hidden;
            margin-top: 5px;
        }

        .health-fill {
            height: 100%;
            background-color: var(--success);
            transition: width 0.5s ease;
        }

        .health-low { background-color: var(--warning); }
        .health-critical { background-color: var(--danger); }

        .requests-container {
            background-color: var(--light);
            border-radius: 8px;
            padding: 15px;
            overflow-y: auto;
            max-height: 100%;
        }

        .requests-container h2 {
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid var(--secondary);
        }

        .request-tabs {
            display: flex;
            margin-bottom: 15px;
            border-bottom: 1px solid #ddd;
        }

        .request-tab {
            padding: 10px 20px;
            cursor: pointer;
            background-color: #eee;
            border: 1px solid #ddd;
            border-bottom: none;
            border-top-left-radius: 5px;
            border-top-right-radius: 5px;
            margin-right: 5px;
        }

        .request-tab.active {
            background-color: white;
            font-weight: bold;
            border-bottom: 1px solid white;
            position: relative;
            top: 1px;
        }

        .request-list {
            display: none;
        }

        .request-list.active {
            display: block;
        }

        .request-card {
            background-color: white;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            border-left: 4px solid var(--pending-color);
        }

        .request-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }

        .request-type {
            font-weight: bold;
            color: var(--primary);
        }

        .request-player {
            font-style: italic;
        }

        .request-content {
            margin: 15px 0;
            padding: 15px;
            background-color: var(--pending-color);
            border-radius: 5px;
            font-family: monospace;
            line-height: 1.8;
        }

        .compound-request {
            font-size: 1.5rem;
            text-align: center;
            padding: 10px;
        }

        .request-properties {
            margin: 15px 0;
        }

        .property-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
            gap: 10px;
            margin-top: 10px;
        }

        .property-item {
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .request-actions {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px solid #eee;
        }

        .no-requests {
            text-align: center;
            padding: 30px;
            color: #888;
            font-style: italic;
        }

        .attack-info {
            background-color: #f8d7da;
            border-left: 4px solid var(--danger);
            padding: 10px;
            border-radius: 4px;
            margin-top: 15px;
            display: none;
        }

        .attack-info.visible {
            display: block;
        }

        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #777;
        }

        .empty-state i {
            font-size: 3rem;
            margin-bottom: 15px;
            color: #ccc;
        }

        .properties-form {
            background-color: #f9f9f9;
            padding: 15px;
            border-radius: 5px;
            margin-top: 15px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }

        select, input {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .game-over {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            display: none;
        }

        .game-over-content {
            background-color: white;
            padding: 40px;
            border-radius: 10px;
            text-align: center;
            max-width: 600px;
        }

        .winner-text {
            font-size: 2rem;
            font-weight: bold;
            color: var(--success);
            margin-bottom: 20px;
        }

        .draw-text {
            font-size: 2rem;
            font-weight: bold;
            color: var(--warning);
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <div class="header-info">
                <h1>化学老师控制台</h1>
                <div class="room-id">房间ID: <span id="room-id">加载中...</span></div>
                <div class="teacher-indicator">化学老师</div>
            </div>
            <div class="game-phase phase-waiting" id="game-phase">等待玩家加入</div>
            <div class="controls">
                <button id="start-game" class="btn-primary">开始游戏</button>
            </div>
        </header>

        <div class="main-content">
            <div class="player-list">
                <h2>玩家列表</h2>
                <div id="players-container">
                    <div class="empty-state">
                        <div>🕵️‍♀️</div>
                        <p>等待玩家加入游戏...</p>
                    </div>
                </div>
            </div>

            <div class="requests-container">
                <h2>审核请求</h2>
                <div class="request-tabs">
                    <div class="request-tab active" data-tab="compound">化合物审核</div>
                    <div class="request-tab" data-tab="reaction">方程式审核</div>
                    <div class="request-tab" data-tab="defense">防御审核</div>
                </div>

                <div id="compound-requests" class="request-list active">
                    <div class="no-requests">没有待审核的化合物请求</div>
                </div>

                <div id="reaction-requests" class="request-list">
                    <div class="no-requests">没有待审核的方程式请求</div>
                </div>

                <div id="defense-requests" class="request-list">
                    <div class="no-requests">没有待审核的防御请求</div>
                </div>
            </div>
        </div>
    </div>

    <div class="game-over" id="game-over">
        <div class="game-over-content">
            <div class="winner-text" id="winner-message">玩家 [获胜者] 赢得了比赛！</div>
            <div class="draw-text" id="draw-message" style="display:none;">游戏平局！</div>
            <button class="btn-primary" id="close-overlay">关闭</button>
        </div>
    </div>

    <script>
        // 获取房间ID
        const roomId = window.location.pathname.split('/').pop();
        let socket = null;
        let currentPlayerSid = '';

        $(document).ready(function() {
            // 显示房间ID
            $('#room-id').text(roomId);

            // 初始化SocketIO连接
            initializeSocket();

            // 标签页切换
            $('.request-tab').click(function() {
                $('.request-tab').removeClass('active');
                $(this).addClass('active');

                const tab = $(this).data('tab');
                $('.request-list').removeClass('active');
                $(`#${tab}-requests`).addClass('active');
            });

            // 开始游戏按钮
            $('#start-game').click(function() {
                socket.emit('start_game');
            });

            // 关闭游戏结束弹窗
            $('#close-overlay').click(function() {
                $('#game-over').hide();
            });
        });

        function initializeSocket() {
            socket = io();

            // 连接到房间
            socket.emit('connect_to_room', {
                room_id: roomId,
                is_teacher: true
            });

            // 监听游戏状态更新
            socket.on('game_state', function(data) {
                currentPlayerSid = socket.id;
                updateGameState(data);
            });

            // 处理审核请求
            socket.on('approval_request', function(request) {
                addApprovalRequest(request);
            });

            // 游戏结束事件
            socket.on('game_over', function(data) {
                showGameOver(data.winner);
            });

            socket.on('game_draw', function() {
                showGameDraw();
            });

            // 接收自己的SID
            socket.on('my_sid', function(sid) {
                currentPlayerSid = sid;
            });
        }

        function updateGameState(state) {
            // 更新阶段显示
            const phaseElement = $('#game-phase');
            phaseElement.removeClass().addClass('game-phase');

            switch(state.game_state) {
                case 'waiting':
                    phaseElement.addClass('phase-waiting').text('等待玩家加入');
                    $('#start-game').prop('disabled', false);
                    break;
                case 'distributing':
                    phaseElement.addClass('phase-distributing').text('发牌阶段');
                    $('#start-game').prop('disabled', true);
                    break;
                case 'preparation':
                    phaseElement.addClass('phase-preparation').text('准备阶段');
                    break;
                case 'action':
                    phaseElement.addClass('phase-action').text('行动阶段');
                    break;
                case 'defense':
                    phaseElement.addClass('phase-defense').text('防御阶段');
                    break;
                case 'settlement':
                    phaseElement.addClass('phase-settlement').text('结算阶段');
                    break;
            }

            // 更新玩家列表
            updatePlayerList(state.players);

            // 更新审核请求列表
            updateApprovalRequests(state.players);
        }

        function updatePlayerList(players) {
            const container = $('#players-container');
            container.empty();

            if (Object.keys(players).length === 0) {
                container.html(`
                    <div class="empty-state">
                        <div>🕵️‍♀️</div>
                        <p>等待玩家加入游戏...</p>
                    </div>
                `);
                return;
            }

            for (const sid in players) {
                const player = players[sid];
                if (player.is_teacher) continue;  // 不显示化学老师自己

                // 计算生命值百分比
                const healthPercent = player.health ? Math.max(0, (player.health / 8) * 100) : 0;
                let healthClass = '';

                if (player.health <= 2) healthClass = 'health-critical';
                else if (player.health <= 4) healthClass = 'health-low';

                // 准备状态
                let statusText = player.is_ready ? '已准备' : '未准备';
                let statusClass = player.is_ready ? 'status-ready' : 'status-not-ready';

                if (player.eliminated) {
                    statusText = '已淘汰';
                    statusClass = 'status-eliminated';
                }

                container.append(`
                    <div class="player-card">
                        <div class="player-header">
                            <div class="player-name">${player.name}</div>
                            <div class="player-status ${statusClass}">${statusText}</div>
                        </div>
                        <div class="player-info">
                            <div>
                                <div>身份: ${player.role}</div>
                                <div>生命值: ${player.health || 0}/8</div>
                            </div>
                            <div>
                                <div>手牌数: ${player.hand_cards_count || 0}</div>
                                <div>反应物: ${player.reaction_area?.length || 0}</div>
                            </div>
                        </div>
                        <div class="health-bar">
                            <div class="health-fill ${healthClass}" style="width: ${healthPercent}%"></div>
                        </div>
                    </div>
                `);
            }
        }

        function updateApprovalRequests(players) {
            // 清空所有请求列表
            $('#compound-requests, #reaction-requests, #defense-requests').empty();

            let hasCompoundRequests = false;
            let hasReactionRequests = false;
            let hasDefenseRequests = false;

            // 收集所有审核请求
            for (const sid in players) {
                const player = players[sid];

                for (const request of player.pending_approvals || []) {
                    // 跳过过期请求
                    if (request.phase !== $('#game-phase').text().replace('阶段', '')) {
                        continue;
                    }

                    if (request.type === 'compound' || (request.type === 'defense_compound' && !request.is_for_defense)) {
                        addCompoundRequestUI(request, player);
                        hasCompoundRequests = true;
                    } else if (request.type === 'reaction') {
                        addReactionRequestUI(request, player);
                        hasReactionRequests = true;
                    } else if (request.type === 'defense_compound' && request.is_for_defense) {
                        addDefenseRequestUI(request, player);
                        hasDefenseRequests = true;
                    }
                }
            }

            // 如果没有请求，显示提示
            if (!hasCompoundRequests) {
                $('#compound-requests').html('<div class="no-requests">没有待审核的化合物请求</div>');
            }
            if (!hasReactionRequests) {
                $('#reaction-requests').html('<div class="no-requests">没有待审核的方程式请求</div>');
            }
            if (!hasDefenseRequests) {
                $('#defense-requests').html('<div class="no-requests">没有待审核的防御请求</div>');
            }
        }

        function addApprovalRequest(request) {
            // 根据请求类型添加到相应列表
            if (request.type === 'compound' || (request.type === 'defense_compound' && !request.is_for_defense)) {
                addCompoundRequestUI(request);
            } else if (request.type === 'reaction') {
                addReactionRequestUI(request);
            } else if (request.type === 'defense_compound' && request.is_for_defense) {
                addDefenseRequestUI(request);
            }
        }

        function addCompoundRequestUI(request, player) {
            // 创建请求卡片
            const card = $(`
                <div class="request-card" data-id="${request.timestamp}">
                    <div class="request-header">
                        <div class="request-type">化合物申请</div>
                        <div class="request-player">来自: ${player ? player.name : request.player_sid}</div>
                    </div>
                    <div class="request-content compound-request">${request.compound}</div>

                    <div class="properties-form">
                        <h3>设置物质属性</h3>
                        <div class="property-grid">
                            <div class="property-item">
                                <input type="checkbox" id="corrosive_concentrated_${request.timestamp}" name="corrosive_concentrated">
                                <label for="corrosive_concentrated_${request.timestamp}">浓腐蚀性</label>
                            </div>
                            <div class="property-item">
                                <input type="checkbox" id="corrosive_diluted_${request.timestamp}" name="corrosive_diluted">
                                <label for="corrosive_diluted_${request.timestamp}">稀腐蚀性</label>
                            </div>
                            <div class="property-item">
                                <input type="checkbox" id="poison_${request.timestamp}" name="poison">
                                <label for="poison_${request.timestamp}">有毒</label>
                            </div>
                            <div class="property-item">
                                <input type="checkbox" id="gas_${request.timestamp}" name="gas">
                                <label for="gas_${request.timestamp}">气体</label>
                            </div>
                            <div class="property-item">
                                <input type="checkbox" id="combustible_${request.timestamp}" name="combustible">
                                <label for="combustible_${request.timestamp}">可燃</label>
                            </div>
                        </div>
                    </div>

                    <div class="request-actions">
                        <button class="btn-danger reject-btn" data-id="${request.timestamp}">驳回</button>
                        <button class="btn-success approve-btn" data-id="${request.timestamp}">批准</button>
                    </div>
                </div>
            `);

            // 添加到化合物请求列表
            $('#compound-requests').append(card);
            $('#compound-requests .no-requests').remove();

            // 添加按钮事件
            card.find('.reject-btn').click(function() {
                const requestId = $(this).data('id');
                socket.emit('approve_request', {
                    id: requestId,
                    approved: false
                });
                card.remove();
            });

            card.find('.approve-btn').click(function() {
                const requestId = $(this).data('id');
                const properties = {
                    corrosive_concentrated: card.find('input[name="corrosive_concentrated"]').is(':checked'),
                    corrosive_diluted: card.find('input[name="corrosive_diluted"]').is(':checked'),
                    poison: card.find('input[name="poison"]').is(':checked'),
                    gas: card.find('input[name="gas"]').is(':checked'),
                    combustible: card.find('input[name="combustible"]').is(':checked')
                };

                socket.emit('approve_request', {
                    id: requestId,
                    approved: true,
                    properties: properties
                });
                card.remove();
            });
        }

        function addReactionRequestUI(request, player) {
            // 格式化方程式
            const equation = request.equation ||
                `${request.reactants.join(' + ')} → ${request.products.join(' + ')}`;

            // 创建请求卡片
            const card = $(`
                <div class="request-card" data-id="${request.timestamp}">
                    <div class="request-header">
                        <div class="request-type">化学反应方程式</div>
                        <div class="request-player">来自: ${player ? player.name : request.player_sid}</div>
                    </div>
                    <div class="request-content">
                        <div><strong>方程式:</strong> ${equation}</div>
                        <div><strong>反应条件:</strong> ${request.action_cards.join(', ')}</div>
                        <div><strong>反应物:</strong> ${request.reactants.join(', ')}</div>
                        <div><strong>生成物:</strong> ${request.products.join(', ')}</div>
                    </div>

                    <div class="request-actions">
                        <button class="btn-danger reject-btn" data-id="${request.timestamp}">驳回</button>
                        <button class="btn-success approve-btn" data-id="${request.timestamp}">批准</button>
                    </div>
                </div>
            `);

            // 添加到反应请求列表
            $('#reaction-requests').append(card);
            $('#reaction-requests .no-requests').remove();

            // 添加按钮事件
            card.find('.reject-btn').click(function() {
                const requestId = $(this).data('id');
                socket.emit('approve_request', {
                    id: requestId,
                    approved: false
                });
                card.remove();
            });

            card.find('.approve-btn').click(function() {
                const requestId = $(this).data('id');
                socket.emit('approve_request', {
                    id: requestId,
                    approved: true
                });
                card.remove();
            });
        }

        function addDefenseRequestUI(request, player) {
            // 创建请求卡片
            const card = $(`
                <div class="request-card" data-id="${request.timestamp}">
                    <div class="request-header">
                        <div class="request-type">防御化合物申请</div>
                        <div class="request-player">来自: ${player ? player.name : request.player_sid}</div>
                    </div>
                    <div class="request-content compound-request">${request.compound}</div>

                    <div class="attack-info ${request.is_under_attack ? 'visible' : ''}">
                        ⚠️ 该玩家正在被攻击，请尽快审核！
                    </div>

                    <div class="properties-form">
                        <h3>设置物质属性</h3>
                        <div class="property-grid">
                            <div class="property-item">
                                <input type="checkbox" id="d_corrosive_concentrated_${request.timestamp}" name="corrosive_concentrated">
                                <label for="d_corrosive_concentrated_${request.timestamp}">浓腐蚀性</label>
                            </div>
                            <div class="property-item">
                                <input type="checkbox" id="d_corrosive_diluted_${request.timestamp}" name="corrosive_diluted">
                                <label for="d_corrosive_diluted_${request.timestamp}">稀腐蚀性</label>
                            </div>
                            <div class="property-item">
                                <input type="checkbox" id="d_poison_${request.timestamp}" name="poison">
                                <label for="d_poison_${request.timestamp}">有毒</label>
                            </div>
                            <div class="property-item">
                                <input type="checkbox" id="d_gas_${request.timestamp}" name="gas">
                                <label for="d_gas_${request.timestamp}">气体</label>
                            </div>
                            <div class="property-item">
                                <input type="checkbox" id="d_combustible_${request.timestamp}" name="combustible">
                                <label for="d_combustible_${request.timestamp}">可燃</label>
                            </div>
                        </div>
                    </div>

                    <div class="request-actions">
                        <button class="btn-danger reject-btn" data-id="${request.timestamp}">驳回</button>
                        <button class="btn-success approve-btn" data-id="${request.timestamp}">批准</button>
                    </div>
                </div>
            `);

            // 添加到防御请求列表
            $('#defense-requests').append(card);
            $('#defense-requests .no-requests').remove();

            // 添加按钮事件
            card.find('.reject-btn').click(function() {
                const requestId = $(this).data('id');
                socket.emit('approve_request', {
                    id: requestId,
                    approved: false
                });
                card.remove();
            });

            card.find('.approve-btn').click(function() {
                const requestId = $(this).data('id');
                const properties = {
                    corrosive_concentrated: card.find('input[name="corrosive_concentrated"]').is(':checked'),
                    corrosive_diluted: card.find('input[name="corrosive_diluted"]').is(':checked'),
                    poison: card.find('input[name="poison"]').is(':checked'),
                    gas: card.find('input[name="gas"]').is(':checked'),
                    combustible: card.find('input[name="combustible"]').is(':checked')
                };

                socket.emit('approve_request', {
                    id: requestId,
                    approved: true,
                    properties: properties
                });
                card.remove();
            });
        }

        function showGameOver(winner) {
            $('#winner-message').text(`玩家 ${winner} 赢得了比赛！`);
            $('#draw-message').hide();
            $('#winner-message').show();
            $('#game-over').show();
        }

        function showGameDraw() {
            $('#winner-message').hide();
            $('#draw-message').show();
            $('#game-over').show();
        }
    </script>
</body>
</html>